<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/16
 * Time: 10:21
 */

namespace app\common\utils;


use think\Log;

final class DateTimeUtil
{
    private function __construct(){
    }

    const WEEK_ARRAY = ["日","一","二","三","四","五","六"];

    /**
     * @param $time
     * @return string
     */
    public static function format($time) :string {

        if (is_numeric($time)) $time = date('Y-m-d H:i:s', $time);

        try{
            $then = new \DateTime($time);
            $now = new \DateTime();

            $dt = $then->diff($now);

            if ($dt->y > 0) {
                return $then->format('Y');
            }
            if ($dt->m > 0) {
                return $then->format('Y/m');
            }

            if ($dt->d > 0) {
                return $then->format('Y/m/d');
            }

            if ($dt->h > 0) return $then->format('今天H:i');
            if ($dt->i > 0) return $then->format('今天H:i:s');

            return '刚刚';

        }catch (\Exception $ex){
            return $time;
        }

    }

    const FORMAT_DATE = 'Y-m-d';
    public static function formatDate($time): string {

        if (is_numeric($time)) $time = date(self::FORMAT_DATE, $time);
        else $time = date(self::FORMAT_DATE, strtotime($time));

        if (date(self::FORMAT_DATE) == $time) {
            return '今天';
        }
        if (date(self::FORMAT_DATE, strtotime('+1 day')) == $time) {
            return '明天';
        }
        if (date(self::FORMAT_DATE, strtotime('-1 day')) == $time) {
            return '昨天';
        }
        return $time;
    }

    public static function formatTime($time): string {
        if (is_string($time)) $time = strtotime($time);
        return date('H:i', $time);
    }

    /**
     * @param int $duration number of seconds
     * @return string
     */
    public static function formatDuration(int $duration): string {

        $values[] = sprintf('%02d',$duration % 60);
        $minutes = intval($duration / 60);
        array_unshift($values, sprintf('%02d',$minutes % 60));
        array_unshift($values, sprintf('%02d', intval($minutes / 60)));

        return implode(':', $values);
    }

}